import validator from "/utils/validators";
import { unitType } from "/utils/dictionary";
import { bus } from "/utils/core"

Component({
  data: {
    form: {
      freeServiceType: "BUY",
      serviceIndex: null,
      name: null,
      count: "",
      freeServiceId: null
    },
    unitType
  },
  props: {
    direction: 'left',
    selectableList: [],
    show: false,
    onEmit: () => { }
  },
  didMount() {
    bus.subscribe('buyServiceFormInit', (form) => {
      this.setData({
        form: form
      })
    })
  },
  didUpdate() { },
  didUnmount() {
    bus.remove('buyServiceFormInit')
  },
  methods: {
    catchMethod() { },
    onFormSubmit(e) {
      Object.assign(this.data.form, e.detail.value);
      let validate = new validator();
      validate.add("checkEmpty", this.data.form.freeServiceType, "类型不能为空");
      validate.add("checkEmpty", this.data.form.name, "服务名称不能为空");
      validate.add("checkIntNotZero", this.data.form.count, "数量不能为空");
      if (validate.check()) {
        this.data.form.totalPrice = this.data.form.count * this.props.selectableList[this.data.form.serviceIndex].price;
        this.props.onEmit({
          form: this.data.form
        });
      }
    },
    hideModal() {
      this.props.onEmit({
        form: null
      })
    },
    onServiceChange(e) {
      this.setData({
        "form.serviceIndex": e.detail.value,
        "form.freeServiceId": this.props.selectableList[e.detail.value].id,
        "form.name": this.props.selectableList[e.detail.value].name,
        "form.unitPrice": this.props.selectableList[e.detail.value].price,
        "form.unit": this.props.selectableList[e.detail.value].unit,
        "form.count": this.props.selectableList[e.detail.value].ext1 ? this.props.selectableList[e.detail.value].ext1 : ""
      });
    },
    onCountInput(e) {
      this.setData({
        "form.count": e.detail.value
      });
    },
    onReduce() {
      if (this.props.selectableList[this.data.form.serviceIndex].ext1 != this.data.form.count) {
        this.data.form.count = +this.data.form.count - parseInt(this.props.selectableList[this.data.form.serviceIndex].ext1);
        this.setData({
          "form.count": this.data.form.count
        });
      }
    },
    onIncrease() {
      this.data.form.count = +this.data.form.count + parseInt(this.props.selectableList[this.data.form.serviceIndex].ext1);
      this.setData({
        "form.count": this.data.form.count
      });
    }
  },
});
